import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { message, Upload } from 'antd';
import React, { useState, useEffect } from 'react';
import Cloud from 'leancloud-storage';

const ImgUpLoad = (props) => {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState();
  useEffect(() => {
    setImageUrl(props.imgUrl);
  }, []);
  // 把图片转换成baes64
  const getBase64 = (img, callback) => {
    const reader = new FileReader();
    reader.readAsDataURL(img);
    reader.addEventListener('load', () => callback(reader.result));
  };
  // 图片上传之前做出处理
  const beforeUpload = (file) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('图片格式只能是jpeg和png!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小最大为2M!');
    }
    // 清空之前图片，以达到加载新图片效果
    return isJpgOrPng && isLt2M && setImageUrl(undefined);
  };
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div
        style={{
          marginTop: 8,
        }}
      >
        Upload
      </div>
    </div>
  );
  // 自定义上传图片函数
  const diyUpLoadFn = (info) => {
    setLoading(true);
    getBase64(info.file, async (base64) => {
      try {
        const file = new Cloud.File('cakeimg.png', { base64 });
        const res = await file.save();
        setImageUrl(res.attributes.url);
        // 把值暴露出去，供表单获取到
        props.onChange(res.attributes.url);
      } finally {
        setLoading(false);
      }
    });
  };
  return (
    <Upload
      name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      customRequest={diyUpLoadFn}
      beforeUpload={beforeUpload}
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{
            width: '112px',
            height: '112px',
          }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  );
};
export default ImgUpLoad;
